package com.fesine.controller;

import com.fesine.entity.Result;
import com.fesine.entity.User;
import com.fesine.service.UserService;
import com.fesine.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @description: 用户控制类
 * @author: Fesine
 * @createTime:2017/8/30 14:59
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/8/30 14:59
 */
@RestController
public class UserController {
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;

    @GetMapping("users")
    public List<User> findAll(){
        return userService.findAll();
    }

    /**
     * 修改使用对象作为参数接受，增加年龄验证功能
     * @param u
     * @param br
     * @return
     */
    @PostMapping("users")
    public Result addUser(@Valid User u, BindingResult br){
        if (br.hasErrors()) {
            return ResultUtil.error(1, br.getFieldError().getDefaultMessage());
        }
        return ResultUtil.success(userService.addUser(u));
    }

    @GetMapping("users/{id}")
    public User findUser(@PathVariable("id") Integer id) {
        return userService.findUser(id);
    }

    @PutMapping("users")
    public User updateUser(@RequestParam("id") Integer id, @RequestParam("name") String name,
                           @RequestParam("age") Integer age) {
        User u = new User();
        u.setId(id);
        u.setName(name);
        u.setAge(age);
        return userService.updateUser(u);
    }

    @DeleteMapping("users/{id}")
    public void deleteUser(@PathVariable("id") Integer id) {
        userService.deleteUser(id);
    }

    @GetMapping("users/age/{age}")
    public List<User> findUserByAge(@PathVariable("age") Integer age) {
        return userService.findUserByAge(age);
    }

    @GetMapping("users/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception {
        userService.getUserAge(id);
    }
}
